/**
 * 使用 API 包装器的产品路由示例
 * 这个文件展示了如何使用新的 API 包装器来简化路由代码
 */

import { getProducts, getProductsCount, createProduct } from '@/lib/database'
import { validateSearchParams, validateProductForm, sanitizeProductData } from '@/lib/validation'
import { uploadFile } from '@/lib/storage'
import { withProductApi, successResponse, errorResponse, paginatedResponse } from '@/lib/api-wrapper'

/**
 * GET /api/products - 获取产品列表
 */
export const GET = withProductApi(async (request) => {
    const { searchParams } = new URL(request.url)

    // 提取并验证查询参数
    const rawParams = {
        search: searchParams.get('search'),
        type: searchParams.get('type'),
        page: searchParams.get('page'),
        limit: searchParams.get('limit'),
        userId: searchParams.get('userId')
    }

    const validatedParams = validateSearchParams(rawParams)

    // 获取产品列表和总数（使用请求中的用户ID）
    const [products, totalCount] = await Promise.all([
        getProducts(validatedParams, request.userId),
        getProductsCount(validatedParams, request.userId)
    ])

    // 计算分页信息
    const totalPages = Math.ceil(totalCount / validatedParams.limit)
    const pagination = {
        currentPage: validatedParams.page,
        totalPages,
        totalCount,
        limit: validatedParams.limit,
        hasNextPage: validatedParams.page < totalPages,
        hasPrevPage: validatedParams.page > 1
    }

    const filters = {
        search: validatedParams.search || null,
        type: validatedParams.type
    }

    return paginatedResponse(products, pagination, filters)
})

/**
 * POST /api/products - 创建新产品
 */
export const POST = withProductApi(async (request) => {
    const contentType = request.headers.get('content-type')
    let body

    // 处理不同的内容类型
    if (contentType?.includes('application/json')) {
        body = await request.json()
    } else if (contentType?.includes('multipart/form-data')) {
        const formData = await request.formData()
        body = {}

        // 提取表单字段
        for (const [key, value] of formData.entries()) {
            if (key !== 'file' && key !== 'thumbnail') {
                body[key] = value
            }
        }

        // 处理文件字段
        const file = formData.get('file')
        const thumbnail = formData.get('thumbnail')

        if (file && file instanceof File) body.file = file
        if (thumbnail && thumbnail instanceof File) body.thumbnail = thumbnail
    } else {
        return errorResponse('INVALID_CONTENT_TYPE', '不支持的内容类型', 400)
    }

    // 验证请求数据
    const validation = validateProductForm(body)
    if (!validation.isValid) {
        return errorResponse('VALIDATION_ERROR', '数据验证失败', 400, validation.errors)
    }

    // 清理和格式化数据
    const productData = sanitizeProductData(body)

    // 处理文件上传
    if (body.file && body.file instanceof File) {
        const uploadResult = await uploadFile(body.file, 'apps')
        if (uploadResult.error) {
            return errorResponse('UPLOAD_FAILED', uploadResult.error, 500)
        }
        productData.file_path = uploadResult.path
        productData.url = uploadResult.url
    }

    // 处理缩略图上传
    if (body.thumbnail && body.thumbnail instanceof File) {
        const uploadResult = await uploadFile(body.thumbnail, 'thumbnails')
        if (uploadResult.error) {
            return errorResponse('UPLOAD_FAILED', uploadResult.error, 500)
        }
        productData.thumbnail_url = uploadResult.url
    }

    // 验证产品类型特定要求
    if (productData.type === 'app' && !productData.file_path && !productData.url) {
        return errorResponse('VALIDATION_ERROR', '应用类型产品必须提供文件路径或下载链接', 400)
    }

    if (productData.type === 'website' && !productData.url) {
        return errorResponse('VALIDATION_ERROR', '网站类型产品必须提供访问链接', 400)
    }

    // 创建产品（使用请求中的用户ID）
    const newProduct = await createProduct(productData, request.userId)

    return successResponse({ product: newProduct }, '产品创建成功', 201)
})